import {queryMenuTree} from '@/request/api'
import router from '@/router'
import store from '../store';
import { getDynamicRouter, setDynamicRouter } from '@/util/LocalStorageUtils'


export async function initDynamicRouter () {
    let {data : menus} = await queryMenuTree({});
    menus.forEach(item =>{
        addRouterItem(item);
    })
}

function addRouterItem(menu,titlePath) {
    if (!titlePath){
        titlePath = [];
    }
    titlePath.push({
        path : menu.router,
        title : menu.title
    })
    if (menu.children){
        menu.children.forEach(item => {
            addRouterItem(item,titlePath);
        })
    }else {
        if (menu.filePath === 'EMPTY') {
            return;
        }
        // let myComponent = () => import('../components/' + menu.filePath + '.vue')
        menu.titlePath = titlePath;
        setDynamicRouter(menu.router, menu);
    }
}

export function addMenuRouter (path) {
    let addFlag = false;
    let menuIsInit = isMenuInit(path);
    if (!menuIsInit){
        let menuRouter = getDynamicRouter(path)
        addRouter(menuRouter);
        addFlag = true;
    }
    return addFlag;
}

function isMenuInit (path) {
    let routerInit = router.getRoutes();
    let isInit = false;
    routerInit.forEach((value) => {
        if (value.path === path){
            isInit =  true;
        }
    })
    return isInit;
}

function addRouter(menu) {
    // let myComponent = () => import('../components/' + menu.filePath + '.vue')
    const path = menu.filePath;
    const aRouter = {
        path: menu.router,
        name: menu.name,
        component: () => import('@/components/'+path+'.vue'),
        meta : {
            titlePath : menu.titlePath
        }
    }
    router.addRoute('home', aRouter)
}
